package com.campusbackend.service.impl;

import com.campusbackend.entity.Teachers;
import com.campusbackend.entity.vo.TeacherRegisterVO;
import com.campusbackend.mapper.TeachersMapper;
import com.campusbackend.service.TeachersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campusbackend.entity.vo.TeacherListVO;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 教师用户表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-07-24
 */
@Service
public class TeachersServiceImpl extends ServiceImpl<TeachersMapper, Teachers> implements TeachersService {

    @Autowired
    private TeachersMapper teachersMapper;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public Teachers findByEmployeeId(String employeeId) {
        return teachersMapper.findByEmployeeId(employeeId);
    }

    @Override
    public boolean isIdCardExists(String idCard) {
        return teachersMapper.countByIdCard(idCard) > 0;
    }

    @Override
    public boolean isPhoneExists(String phone) {
        return teachersMapper.countByPhone(phone) > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        return teachersMapper.countByEmail(email) > 0;
    }

    @Override
    public String registerTeacher(TeacherRegisterVO registerVO) {
    // 1. 检查密码确认
        if (!registerVO.getPassword().equals(registerVO.getConfirmPassword())) {
            return "两次输入的密码不一致";
        }

        // 2. 检查工号是否已存在
        if (isEmployeeIdExists(registerVO.getEmployee_id())) {
            return "该工号已存在，请使用其他工号";
        }
        
        // 3. 检查身份证号是否已存在
        if (isIdCardExists(registerVO.getId_card())) {
            return "该身份证号已被注册，请检查身份证号是否正确";
        }
        
        // 4. 检查手机号是否已存在
        if (isPhoneExists(registerVO.getPhone())) {
            return "该手机号已被注册，请使用其他手机号";
        }
        
        // 5. 检查邮箱是否已存在
        if (isEmailExists(registerVO.getEmail())) {
            return "该邮箱已被注册，请使用其他邮箱";
        }

        try {
            // 3. 创建教师实体
            Teachers teacher = new Teachers();
            teacher.setEmployeeId(registerVO.getEmployee_id());
            // 设置username为工号，因为登录时使用工号
            teacher.setUsername(registerVO.getEmployee_id());
            // 加密密码
            teacher.setPassword(passwordEncoder.encode(registerVO.getPassword()));
            teacher.setRealName(registerVO.getReal_name());
            teacher.setPhone(registerVO.getPhone());
            teacher.setEmail(registerVO.getEmail());
            teacher.setProfessionalTitle(registerVO.getProfessional_title());
            teacher.setIdCard(registerVO.getId_card());
            
            // 设置默认值
            teacher.setAuditStatus((byte) 0); // 0-待审核
            teacher.setStatus((byte) 1); // 1-正常状态
            teacher.setCreateTime(LocalDateTime.now());
            teacher.setUpdateTime(LocalDateTime.now());

            // 4. 保存到数据库
            boolean saved = save(teacher);
            if (saved) {
                return "注册成功，请等待管理员审核";
            } else {
                return "注册失败，请稍后重试";
            }
        } catch (Exception e) {
            return "注册过程中发生错误：" + e.getMessage();
        }
    }

    @Override
    public boolean isEmployeeIdExists(String employeeId) {
        return teachersMapper.countByEmployeeId(employeeId) > 0;
    }

    @Override
    public String updateBasicInfo(String employeeId, String phone, String email, String professionalTitle, String idCard) {
        try {
            // 1. 检查当前用户是否存在
            Teachers currentTeacher = findByEmployeeId(employeeId);
            if (currentTeacher == null) {
                return "用户不存在";
            }

            // 2. 检查手机号是否被其他用户占用
            if (!phone.equals(currentTeacher.getPhone()) && isPhoneExistsExcludeCurrentUser(phone, employeeId)) {
                return "该手机号已被其他用户注册，请使用其他手机号";
            }

            // 3. 检查邮箱是否被其他用户占用
            if (!email.equals(currentTeacher.getEmail()) && isEmailExistsExcludeCurrentUser(email, employeeId)) {
                return "该邮箱已被其他用户注册，请使用其他邮箱";
            }

            // 4. 检查身份证号是否被其他用户占用
            if (!idCard.equals(currentTeacher.getIdCard()) && isIdCardExistsExcludeCurrentUser(idCard, employeeId)) {
                return "该身份证号已被其他用户注册，请检查身份证号是否正确";
            }

            // 5. 更新基本信息
            currentTeacher.setPhone(phone);
            currentTeacher.setEmail(email);
            currentTeacher.setProfessionalTitle(professionalTitle);
            currentTeacher.setIdCard(idCard);
            currentTeacher.setUpdateTime(LocalDateTime.now());

            // 6. 保存更新
            boolean updated = updateById(currentTeacher);
            if (updated) {
                return "基本信息更新成功";
            } else {
                return "基本信息更新失败，请稍后重试";
            }

        } catch (Exception e) {
            return "更新基本信息时发生错误：" + e.getMessage();
        }
    }

    @Override
    public String updatePersonalHomepage(String employeeId, String personalHomepage) {
        try {
            // 1. 检查当前用户是否存在
            Teachers currentTeacher = findByEmployeeId(employeeId);
            if (currentTeacher == null) {
                return "用户不存在";
            }

            // 2. 更新个人主页
            currentTeacher.setPersonalHomepage(personalHomepage);
            currentTeacher.setUpdateTime(LocalDateTime.now());

            // 3. 保存更新
            boolean updated = updateById(currentTeacher);
            if (updated) {
                return "个人主页更新成功";
            } else {
                return "个人主页更新失败，请稍后重试";
            }

        } catch (Exception e) {
            return "更新个人主页时发生错误：" + e.getMessage();
        }
    }

    @Override
    public List<TeacherListVO> getAllTeachers() {
        // 查询所有正常状态的教师
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 只查询正常状态的教师
                   .eq("audit_status", 1) // 只查询审核通过的教师
                   .orderByDesc("create_time"); // 按创建时间倒序
        
        List<Teachers> teachers = teachersMapper.selectList(queryWrapper);
        
        // 转换为VO对象
        return teachers.stream().map(this::convertToTeacherListVO).collect(Collectors.toList());
    }

    @Override
    public List<TeacherListVO> searchTeachers(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getAllTeachers(); // 如果没有关键词，返回所有教师
        }
        return teachersMapper.searchTeachers(keyword.trim());
    }

    /**
     * 转换Teachers实体为TeacherListVO
     * @param teacher 教师实体
     * @return TeacherListVO
     */
    private TeacherListVO convertToTeacherListVO(Teachers teacher) {
        TeacherListVO vo = new TeacherListVO();
        vo.setTeacherId(teacher.getId());
        vo.setEmployeeId(teacher.getEmployeeId());
        vo.setUsername(teacher.getUsername());
        vo.setRealName(teacher.getRealName());
        vo.setPhone(teacher.getPhone());
        vo.setEmail(teacher.getEmail());
        vo.setIdCard(teacher.getIdCard());
        vo.setProfessionalTitle(teacher.getProfessionalTitle());
        vo.setPersonalHomepage(teacher.getPersonalHomepage());
        vo.setAvatar(teacher.getAvatar());
        vo.setAuditStatus(teacher.getAuditStatus());
        vo.setStatus(teacher.getStatus());
        vo.setCreateTime(teacher.getCreateTime());
        return vo;
    }

    /**
     * 检查手机号是否被其他用户占用（排除当前用户）
     */
    private boolean isPhoneExistsExcludeCurrentUser(String phone, String employeeId) {
        return teachersMapper.countByPhoneExcludeCurrentUser(phone, employeeId) > 0;
    }

    /**
     * 检查邮箱是否被其他用户占用（排除当前用户）
     */
    private boolean isEmailExistsExcludeCurrentUser(String email, String employeeId) {
        return teachersMapper.countByEmailExcludeCurrentUser(email, employeeId) > 0;
    }

    /**
     * 检查身份证号是否被其他用户占用（排除当前用户）
     */
    private boolean isIdCardExistsExcludeCurrentUser(String idCard, String employeeId) {
        return teachersMapper.countByIdCardExcludeCurrentUser(idCard, employeeId) > 0;
    }
}
